package com.fr.lintcode;

import java.util.ArrayList;
import java.util.Collections;

import org.junit.Test;

/**
*作者：furong
*日期：2017年1月18日
*时间：下午1:31:40
*/
public class Q11 {
    /**
     * @param root: The root of the binary search tree.
     * @param k1 and k2: range k1 to k2.
     * @return: Return all keys that k1<=key<=k2 in ascending order.
     */
    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
        ArrayList<Integer> rs = new ArrayList<>();
        searchRange(root, k1, k2, rs);
        Collections.sort(rs);
        return rs;
    }

    private void searchRange(TreeNode node, int k1, int k2, ArrayList<Integer> rs) {
        if (node == null) {
            return;
        }
        if (node.val < k1) {
            searchRange(node.right, k1, k2, rs);
        } else if (node.val <= k2) {
            rs.add(node.val);
            searchRange(node.left, k1, k2, rs);
            searchRange(node.right, k1, k2, rs);
        } else {
            searchRange(node.left, k1, k2, rs);
        }
    }

    @Test
    public void testA() {
        TreeNode root = new TreeNode(5);
        TreeNode r1 = new TreeNode(3);
        TreeNode r2 = new TreeNode(8);
        TreeNode r3 = new TreeNode(1);
        TreeNode r4 = new TreeNode(2);
        TreeNode r5 = new TreeNode(9);
        root.left = r1;
        root.right = r2;
        r1.left = r3;
        r2.right = r5;
        r3.right = r4;
        System.out.println(searchRange(root, 1, 4));
    }
}
